package pl.edu.agh.sius.invokers;

import java.util.List;
import java.util.Map;

import javax.activation.DataHandler;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.soap.MTOMFeature;
import javax.xml.ws.soap.SOAPBinding;

import pl.edu.agh.sius.schema.simplep2pserver.DownloadRequestWrapper;
import pl.edu.agh.sius.schema.simplep2pserver.DownloadResponseWrapper;
import pl.edu.agh.sius.schema.simplep2pserver.FileInfo;
import pl.edu.agh.sius.schema.simplep2pserver.FilesListWrapper;
import pl.edu.agh.sius.wsdl.simplep2pserver.SimpleP2PServerPortType;
import pl.edu.agh.sius.wsdl.simplep2pserver.SimpleP2PServerService;

import com.sun.xml.ws.developer.JAXWSProperties;

public class SimpleServerInvoker {
	
	private SimpleP2PServerService service;
	private SimpleP2PServerPortType port;
	

	public void setService(SimpleP2PServerService service, String endpoint) {
		this.service = service;
		this.port = service.getSimpleP2PServerPort(new MTOMFeature());
		
		BindingProvider bp=(BindingProvider)port;
		SOAPBinding binding = (SOAPBinding) bp.getBinding();
		
		binding.setMTOMEnabled(true);
		
		Map<String, Object> ctx = bp.getRequestContext();	
		ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpoint);
		//ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:7777/simple-server/services/SimpleP2PServer");
		ctx.put(JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, 256);
		
	}
	
	public SimpleP2PServerService getService() {
		return service;
	}
	
	public DataHandler download(FileInfo fileInfo){
		DownloadRequestWrapper drw = new DownloadRequestWrapper();
		drw.setResourceId(fileInfo.getFileId());
		DownloadResponseWrapper downloadResponseWrapper = port.download(drw);
		return downloadResponseWrapper.getFile();
	}

	public List<FileInfo> getFilesList() {
		FilesListWrapper filesListWrapper = port.getFilesList();
		return filesListWrapper.getItems();
	}
}